package com.lw.system.service.impl;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lw.common.constant.LoginConstant;
import com.lw.common.core.dao.BaseDAO;
import com.lw.common.core.service.BaseService;
import com.lw.common.exceptions.BizException;
import com.lw.common.exceptions.LoginException;
import com.lw.common.util.Encrypt;
import com.lw.system.dao.UserMapper;
import com.lw.system.dao.UserRoleMapper;
import com.lw.system.model.User;
import com.lw.system.model.UserRole;
import com.lw.system.service.UserService;

/**
 * 
 * @Title: UserServiceImpl.java
 * @Package com.lw.service.impl
 * @Description: 用户service
 * @author 刘伟 15818570028@163.com
 * @date 2016年12月21日 下午6:57:07
 * @version V1.0
 */
@Service("userService")
public class UserServiceImpl extends BaseService<User, String> implements UserService {
	@Resource
	private UserMapper userMapper;
	@Resource
	private UserRoleMapper userRoleMapper;

	@Override
	public BaseDAO<User, String> getDao() {
		return userMapper;
	}

	@Override
	public User login(User u) {
		if (StringUtils.isEmpty(u.getLoginName()) || StringUtils.isEmpty(u.getLoginName())) {
			throw LoginException.LOGIN_PARAM_0;
		}
		return userMapper.login(u);
	}

	@Override
	public PageInfo<User> findUserAndRoles(User u, int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		List<User> list = userMapper.findUserAndRoles(u);
		return new PageInfo<User>(list);
	}

	@Override
	public int edit(User u) {
		int updateByPrimaryKey = userMapper.updateByPrimaryKeySelective(u);
		if (updateByPrimaryKey == 0) {
			throw BizException.DB_UPDATE_RESULT_0;
		} else {
			userRoleMapper.deleteUserRoleByUserId(u.getId());
			if (u.getRoleIds() != null) {
				for (String roleId : u.getRoleIds().split(",")) {
					UserRole ur = new UserRole();
					ur.setId(UUID.randomUUID().toString());
					ur.setUserId(u.getId());
					ur.setRoleId(roleId);
					int insert = userRoleMapper.insert(ur);
					if (insert == 0) {
						throw BizException.DB_INSERT_RESULT_0;
					}

				}
			}
		}
		return updateByPrimaryKey;
	}

	@Override
	public int insertSelective(User record) {
		if (StringUtils.isEmpty(record.getId())) {
			record.setId(UUID.randomUUID().toString());
		}
		record.setCreatetime(new Date());
		record.setStatus(LoginConstant.NORMAL_USER);
		record.setType("1");
		record.setPassword(Encrypt.sha256Hash(record.getPassword()));
		return super.insertSelective(record);
	}

	@Override
	public User findUserByLoginName(String loginName) {
		if (StringUtils.isEmpty(loginName)) {
			throw LoginException.LOGIN_PARAM_0;
		}
		return userMapper.findUserByLoginName(loginName);

	}

}
